package gprc

import (
	"context"
	"time"
	pbCity "wire/api/city"
	pbUser "wire/api/user"

	"gitee.com/go-mod/framework/config"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
)

type Client struct {
	conn       *grpc.ClientConn
	ctx        context.Context
	ctxCancel  context.CancelFunc
	userClient pbUser.UserClient
	cityClient pbCity.CityClient
}

// NewClient
func NewClient() *Client {
	config.Init()

	// 连接server端
	conn, err := grpc.NewClient(config.GetString("grpc-client.addr"), grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		panic(err)
	}

	// 设置超时
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)

	return &Client{
		ctx:        ctx,
		ctxCancel:  cancel,
		conn:       conn,
		userClient: pbUser.NewUserClient(conn),
		cityClient: pbCity.NewCityClient(conn),
	}
}

func (c *Client) UserGet(req *pbUser.GetRequest) (*pbUser.UserInfo, error) {
	return c.userClient.Get(c.ctx, req)
}

func (c *Client) CityAll(req *pbCity.AllRequest) (*pbCity.AllReply, error) {
	return c.cityClient.All(c.ctx, req)
}

func (c *Client) Close() {
	c.conn.Close()
	c.ctxCancel()
}
